/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhie.desktop.ilo.importer.ui;

import com.kungkhies.desktop.ilo.explorer.IloExplorerTopComponent;
import com.kungkhies.desktop.ilo.importer.service.IloImporterService;
import com.kungkhies.desktop.library.entities.Ilo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.swing.JFileChooser;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.NotifyDescriptor.Confirmation;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//com.kungkhie.desktop.ilo.importer.ui//IloImporterUi//EN",
autostore = false)
@TopComponent.Description(preferredID = "IloImporterUiTopComponent",
//iconBase="SET/PATH/TO/ICON/HERE", 
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.kungkhie.desktop.ilo.importer.ui.IloImporterUiTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(displayName = "#CTL_IloImporterUiAction",
preferredID = "IloImporterUiTopComponent")
public final class IloImporterUiTopComponent extends TopComponent
{
    private IloImporterService iloImporterService;
    private int returnVal;
    private JFileChooser jFileChooser1;

    public IloImporterUiTopComponent()
    {
        initComponents();
        setName(NbBundle.getMessage(IloImporterUiTopComponent.class, "CTL_IloImporterUiTopComponent"));
        setToolTipText(NbBundle.getMessage(IloImporterUiTopComponent.class, "HINT_IloImporterUiTopComponent"));

        jFileChooser1 = new JFileChooser();
        iloTextArea.setEditable(false);

        ActionListener actionListener = new ActionListener()
        {
            public void actionPerformed(ActionEvent actionEvent)
            {
                jFileChooser1 = (JFileChooser) actionEvent.getSource();
                String command = actionEvent.getActionCommand();
                if (command.equals(JFileChooser.APPROVE_SELECTION))
                {
                    File selectedFile = jFileChooser1.getSelectedFile();
                    System.out.println(selectedFile.getParent());
                    selectedFileTextField.setText(selectedFile.getName());
                    iloTextArea.setText("");
                    readFileIntoTextArea(selectedFile);
                }
                else if (command.equals(JFileChooser.CANCEL_SELECTION))
                {
                    System.out.println(JFileChooser.CANCEL_SELECTION);
                }
            }
        };

        jFileChooser1.addActionListener(actionListener);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        iloTextArea = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        selectedFileTextField = new javax.swing.JTextField();
        chooseFileButton = new javax.swing.JButton();
        importIlosButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        iloPackageTextField = new javax.swing.JTextField();
        cancelButton = new javax.swing.JButton();

        iloTextArea.setColumns(20);
        iloTextArea.setRows(5);
        iloTextArea.setMaximumSize(new java.awt.Dimension(200, 200));
        jScrollPane1.setViewportView(iloTextArea);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.jLabel1.text")); // NOI18N
        jLabel1.setDoubleBuffered(true);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.jLabel2.text")); // NOI18N

        selectedFileTextField.setColumns(20);
        selectedFileTextField.setText(org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.selectedFileTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(chooseFileButton, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.chooseFileButton.text")); // NOI18N
        chooseFileButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                chooseFileButtonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(importIlosButton, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.importIlosButton.text")); // NOI18N
        importIlosButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                importIlosButtonMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.jLabel3.text")); // NOI18N

        iloPackageTextField.setColumns(30);
        iloPackageTextField.setText(org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.iloPackageTextField.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(IloImporterUiTopComponent.class, "IloImporterUiTopComponent.cancelButton.text")); // NOI18N
        cancelButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cancelButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(53, 53, 53)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(selectedFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(chooseFileButton))
                            .addComponent(jLabel1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
                            .addComponent(jLabel3)
                            .addComponent(iloPackageTextField)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(importIlosButton, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addGap(59, 59, 59))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(85, 85, 85)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(selectedFileTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(chooseFileButton))
                .addGap(49, 49, 49)
                .addComponent(jLabel1)
                .addGap(28, 28, 28)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(iloPackageTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(importIlosButton)
                    .addComponent(cancelButton))
                .addContainerGap(116, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void chooseFileButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_chooseFileButtonMouseClicked
    {//GEN-HEADEREND:event_chooseFileButtonMouseClicked
        returnVal = jFileChooser1.showOpenDialog(this);
    }//GEN-LAST:event_chooseFileButtonMouseClicked

    private void importIlosButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_importIlosButtonMouseClicked
    {//GEN-HEADEREND:event_importIlosButtonMouseClicked
        IloSaveCapability isc = new IloSaveCapability();
        try
        {
            isc.save();
        }
        catch (IOException ex)
        {
            Exceptions.printStackTrace(ex);
        }

        IloExplorerTopComponent.refreshNode();
        
        clearAndClose();
    }//GEN-LAST:event_importIlosButtonMouseClicked

    /**
     * Clear text fields and close window.
     * 
     * @param evt 
     */
    private void cancelButtonMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_cancelButtonMouseClicked
    {//GEN-HEADEREND:event_cancelButtonMouseClicked
        clearAndClose();
    }//GEN-LAST:event_cancelButtonMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton chooseFileButton;
    private javax.swing.JTextField iloPackageTextField;
    private javax.swing.JTextArea iloTextArea;
    private javax.swing.JButton importIlosButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField selectedFileTextField;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened()
    {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed()
    {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p)
    {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p)
    {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    public List<Ilo> getIloList(DataObject dob)
    {
        return null;
    }

    public void readFileIntoTextArea(File selectedFile)
    {
        FileObject fileObject = FileUtil.toFileObject(FileUtil.normalizeFile(selectedFile));

        try
        {
            InputStream is = fileObject.getInputStream();

            InputStreamReader reader = new InputStreamReader(is);

            BufferedReader buf = new BufferedReader(reader);

            String line;
            try
            {
                while ((line = buf.readLine()) != null)
                {
                    iloTextArea.append(line + "\n");
                }
            }
            catch (IOException ex)
            {
                Exceptions.printStackTrace(ex);
            }

        }
        catch (FileNotFoundException ex)
        {
            Exceptions.printStackTrace(ex);
        }
    }

    public List<Ilo> getIloList()
    {
        File selectedFile = jFileChooser1.getSelectedFile();
        FileObject fileObject = FileUtil.toFileObject(FileUtil.normalizeFile(selectedFile));

        List<Ilo> iloList = new ArrayList<Ilo>();

        String packageString = iloPackageTextField.getText();

        try
        {
            InputStream is = fileObject.getInputStream();

            InputStreamReader reader = new InputStreamReader(is);

            BufferedReader buf = new BufferedReader(reader);

            String line;
            try
            {
                while ((line = buf.readLine()) != null)
                {
                    if (!packageString.equals("") && !line.equals(""))
                    {
                        Ilo ilo = new Ilo();
                        ilo.setPackage1(packageString);
                        ilo.setIloText(line);
                        iloList.add(ilo);
                    }
                }
            }
            catch (IOException ex)
            {
                Exceptions.printStackTrace(ex);
            }



        }
        catch (FileNotFoundException ex)
        {
            Exceptions.printStackTrace(ex);
        }

        return iloList;
    }

    private class IloSaveCapability implements SaveCookie
    {
        @Override
        public void save() throws IOException
        {

            Confirmation message = new NotifyDescriptor.Confirmation("Do you want to save?",
                    NotifyDescriptor.OK_CANCEL_OPTION,
                    NotifyDescriptor.QUESTION_MESSAGE);

            Object result = DialogDisplayer.getDefault().notify(message);
            //When user clicks "Yes", indicating they really want to save,
            //we need to disable the Save action,
            //so that it will only be usable when the next change is made
            //to the JTextArea:
            if (NotifyDescriptor.YES_OPTION.equals(result))
            {
                List<Ilo> iloList = getIloList();
                EntityManager entityManager = Persistence.createEntityManagerFactory("KungkhieEntityLibraryPU").createEntityManager();
                entityManager.getTransaction().begin();

                for (Ilo ilo : iloList)
                {
                    if (!ilo.getPackage1().equals("") && !ilo.getIloText().equals(""))
                    {
                        ilo.setPackage1(ilo.getPackage1());
                        ilo.setIloText(ilo.getIloText());
                        entityManager.persist(ilo);
                    }


                }


                entityManager.getTransaction().commit();
            }
        }
    }
    
    public void clearAndClose()
    {
        iloTextArea.setText("");
        selectedFileTextField.setText("");
        iloPackageTextField.setText("");
        this.close();   
    }
    
    
}
